<template>
	<view class="downloadVisa">
		<!-- #ifdef MP-WEIXIN -->
		<view class="custum-head"></view>
		<view class="head">

			<view class="left" @tap="onBack">
				<u-icon name="arrow-left" color="#fff" size="40"></u-icon>
			</view>
			<view class="title">订单列表</view>


		</view>
		<!-- #endif -->

		<view class="headBac">

			<view class="signOut">
				<view class="img">
					<image class="icon_img" :src="url + '/images/entryOrder/success.png'" mode="heightFix" />
				</view>
				<view class="success">恭喜！出签成功</view>
			</view>

			<view class="itemBodyTitle">
				<view class="img">
					<image class="icon_img" :src="visa.NationalFlag" />
				</view>
				<view class="txt">{{ visa.Zh_name }}{{ visa.VisaTitle }} 【{{ visa.areaName }}】</view>
			</view>

			<view class="look">
				<view class="txt" data-name="1" @click="toH5">查看资料</view>
				<view class="icon iconn">
					<image :src="url + '/arrow2.png'" mode="widthFix"></image>
					<!-- <u-icon name="arrow-right" color="#1C71F4" size="26"></u-icon> -->
				</view>
			</view>


		</view>
		<view class="signOutPersonInfo">
			<view class="content">
				<view class="itemPerson" v-for="(item, index) in mdacList" :key="index">
					<view class="leftInfo">
						<view class="name">{{ item.Cname }}</view>
						<!-- <view class="allPerson">{{OrderDetails.PeopleType}}</view> -->
					</view>
					<view style="width: 60%;display: flex;justify-content:flex-end">
						<view class="downLoad" data-type="0" v-if="item.SuccessPdf" style="margin-right: 30rpx;"
							:data-paymentstatus="item.PaymentStatus" :data-pdfurl="item.SuccessPdf"
							@click="downloadFile"> {{ item.PaymentStatus != 1 ? '待提交' : '下载签证' }} </view>
						<view class="downLoad" v-if="visa.VisaId=='2189066fd2a943ee8ab5711535fbce9e'" data-type="1" :data-paymentstatus="item.PaymentStatus"
							:data-pdfurl="item.SuccessArrivalPdf" @click="downloadFile">
							{{item.PaymentStatus != 1 ? '待提交' : '下载入境卡'}}
						</view>
					</view>

				</view>
			</view>
		</view>
		<view class="progress-container" v-if="isShowProgress">
			<view class="progress-box">
				<view class="text">文件下载中，请稍后......</view>
				<progress :percent="progress" show-info stroke-width="3" />
			</view>
		</view>
		<authorize @onLoadFun='onLoadFun' @onCloseAuto='onCloseAuto' :isGoIndex='isGoIndex' :iShidden='iShidden'>
		</authorize>
	</view>
</template>

<script>
	import {
		getPassenger,
		refundPassenger,
		ExportZip,
	} from '../../api/order.js'
	import {
		sendEmailByUrl,
		wordToPDF
	} from '@/api/api.js'
	let app = getApp()
	import authorize from "@/component/authorize/authorize.vue";
	import uCellGroup from "@/uview-ui/components/u-cell-group/u-cell-group.vue";

	export default {
		data() {
			return {
				// url2: 'https://file.aavisa.com/002',
				url: "https://file.aavisa.com/001",
				list: [{
						name: "蔡佳悦",
						allPerson: "所有人群",
					},
					{
						name: "李丽丽",
						allPerson: "所有人群",
					},
				],
				remark: null, // 原因
				isRemark: false, //原因单选框控制  
				OrderDetails: {},
				visa: {},
				mdacList: [],
				indexStus: '', // 状态码
				posterImageStatus: false,
				isGoIndex: true,
				iShidden: true,
				orderId: '',

				wordUrl: '',
				wordType: '',
				wordName: '',
				email: '',
				emailMsg: '',
				emailText: '发送',

				emailShow: false,
				isInternalSources: false, //是否内部来源  外部来源隐藏标题及操作按钮
				isShowProgress: false,
				progress: 0,
			};
		},
		components: {
			authorize,
			uCellGroup
		},
		onLoad: function(options) {
			let onLaunch_Options = uni.getStorageSync('onLaunch_app')
			let onShow_Options = uni.getStorageSync('onShow_app')
			if (onLaunch_Options && onLaunch_Options.path == 'pages/visa/list' && onLaunch_Options.query) {
				options = onLaunch_Options.query
			} else if (onShow_Options && onShow_Options.path == 'pages/visa/list' && onShow_Options.query) {
				options = onShow_Options.query
			}

			if (app.globalData.token) {
				this.setData({
					iShidden: true,
					orderId: options.orderId || '',
				});
			} else {
				this.setData({
					orderId: options.orderId || '',
				});
			}
		},
		onShow: function() {
			console.log(getApp().globalData.isLog)
			if (getApp().globalData.isLog) {
				this.getPassenger()
			}
		},

		methods: {
			onBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			toInfoMation() {
				uni.navigateTo({
					url: "/pages/startProcess/index",
				});
			},
			onLoadFun: function() {
				this.getPassenger();
			},
			onCloseAuto: function() {
				this.setData({
					iShidden: true
				});
			},
			// 获取旅客申请进展信息
			async getPassenger() {

				let res = await getPassenger(this.orderId);
				console.log(res, '获取旅客申请进展信息')
				let {
					status,
					data
				} = res;
				data.data.latestStatus ? data.data.latestStatus = data.data.latestStatus.split('--') : ""
				if (status == 200) {
					this.setData({
						OrderDetails: data.data,
						visa: data.visa,
						indexStus: data.data.status,
						mdacList: data.mdacList
					})
				}
			},
			downloadFile(e) {
				debugger
				let pdfUrl = e.currentTarget.dataset.pdfurl;
				let type = e.currentTarget.dataset.type;
				if (!pdfUrl) {
					if (type == "1") {
						uni.showToast({
							title: '入境卡将在入境前两天生成，请耐心等待',
							icon: 'none'
						});
					}

				}
				console.log(pdfUrl, "pdfUrl")
				// #ifndef MP-WEIXIN

				const downloadTask = uni.downloadFile({
    url: pdfUrl,
    success: (downloadRes) => {
        if (downloadRes.statusCode === 200) {
            const tempFilePath = downloadRes.tempFilePath;
            const fileExt = tempFilePath.split('.').pop().toLowerCase(); // 获取文件扩展名
            
            // 判断是否为图片类型
            if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp','image'].includes(fileExt)) {
                // 直接保存图片到相册
                uni.saveImageToPhotosAlbum({
                    filePath: tempFilePath,
                    success: () => {
                        // uni.showToast({
                        //     title: '图片已保存到相册',
                        //     icon: 'success',
                        //     duration: 2000
                        // });
                    },
                    fail: (err) => {
                        console.error('保存图片失败:', err);
                        uni.showToast({
                            title: '保存失败，请检查权限设置',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                });
            } else {
                // 非图片文件：保存到本地
                uni.saveFile({
                    tempFilePath: tempFilePath,
                    success: (saveRes) => {
                        const savedFilePath = saveRes.savedFilePath;
                        // 使用您提供的模态框样式
                        uni.showModal({
                            title: '温馨提示',
                            content: '文件已下载成功',
                            showCancel: false,
                            confirmText: '打开文件',
                            success: function(modalRes) {
                                if (modalRes.confirm) {
                                    uni.openDocument({
                                        showMenu: true, // 可以分享
                                        filePath: savedFilePath, // 注意变量名是savedFilePath，之前代码中写成了red.savedFilePath，这里修正
                                        success: (sus) => {
                                            console.log('成功打开');
                                        },
                                        fail: (err) => {
                                            console.error('打开文档失败', err);
                                            uni.showToast({
                                                title: '打开文档失败',
                                                icon: 'none'
                                            });
                                        }
                                    });
                                }
                            }
                        });
                    },
                    fail: (err) => {
                        console.error('保存文件失败:', err);
                        uni.showToast({
                            title: '文件保存失败',
                            icon: 'none'
                        });
                    }
                });
            }
        }
    },
    fail: (downloadErr) => {
        console.error('下载失败:', downloadErr);
        uni.showToast({
            title: '文件下载失败',
            icon: 'none'
        });
    }
});
				// #endif
				// #ifdef MP-WEIXIN
				if (pdfUrl) {
					wx.downloadFile({
						url: pdfUrl,
						success: (data) => {
							if (data.statusCode === 200) {
								wx.saveFile({
									tempFilePath: data.tempFilePath,
									success: (res) => {
										setTimeout(() => {
											wx.openDocument({
												filePath: res.savedFilePath,
												showMenu: true,
												success: () => wx.hideLoading(),
												fail: () => wx.hideLoading()
											});
										}, 3000);
									}
								});
							}
						},
						fail: (err) => {
							console.error(err);
						}
					});
				}
				// #endif

			},
			onDownLoadpdf(e) {
				console.log(e)
				let pdfUrl = e.currentTarget.dataset.pdfurl;
				let paymentstatus = e.currentTarget.dataset.paymentstatus;
				uni.showLoading({
					title: '下载中'
				})
				console.log(pdfUrl, "pdfUrl")
				console.log(paymentstatus, "paymentstatus")
				if (pdfUrl && paymentstatus == 1) {
					uni.downloadFile({
						url: pdfUrl,
						success: (data) => {
							if (data.statusCode === 200) {
								//文件保存到本地
								console.log(data)
								uni.saveFile({
									tempFilePath: data.tempFilePath, //临时路径
									success: function(res) {
										console.log(res)
										uni.hideLoading()
										// uni.showToast({
										// 	icon: 'none',
										// 	mask: true,
										// 	title: '文件已保存：' + res.savedFilePath, //保存路径
										// 	duration: 3000,
										// });
										uni.showModal({
											title: '提示',
											content: '文件已保存：' + res.savedFilePath,
											// cancelText: '我知道了',
											confirmText: '打开文件',
											success: function(res) {
												if (res.confirm) {
													uni.openDocument({
														showMenu: true, //是否可以分享
														filePath: res
															.savedFilePath,
														success: (sus) => {
															console.log(
																'成功打开');
														}
													})
												}
											}
										});
										// setTimeout(() => {
										// 	//打开文档查看
										// 	uni.openDocument({
										// 		filePath: res.savedFilePath,
										// 		showMenu: true, //是否可以分享
										// 		success: function(res) {
										// 			// console.log('打开文档成功');
										// 			uni.hideLoading()
										// 		},
										// 		fail: function() {
										// 			uni.hideLoading()
										// 		}
										// 	});
										// }, 3000)
									},
									fail: function() {
										uni.hideLoading()
									}
								});
							}

						},
						fail: function(err) {
							reject(temp + JSON.stringify(err));
							uni.hideLoading()
						}
					});


				}
			},

			// 跳转H5
			toH5(e) {
				console.log(e)
				let url = null;
				let memberid = getApp().globalData.userInfo.MemberId;
				e.currentTarget.dataset.name == '1' ? url = encodeURIComponent(this.OrderDetails.url + "&memberid=" +
						memberid + "&newui=true") : url =
					encodeURIComponent(this.OrderDetails.headUpdateUrl);
				getApp().goToPage(`/pages/uploadDataByH5/index?url=${url}`)
			},
			// 跳转客服页
			toAdvisory() {
				getApp().goToPage(`/pages/user/advisory`)
			},
			prveImg() {
				if (!this.OrderDetails.interviewPath) return;
				uni.previewImage({
					urls: [`${this.OrderDetails.interviewPath}`],
				})
			},
			// 打开签证页预览
			onPosterClose() {
				this.setData({
					posterImageStatus: !this.posterImageStatus
				})
			},
			prveImg() {
				if (!this.OrderDetails.visaPage) return;
				uni.previewImage({
					urls: [`${this.OrderDetails.visaPage}`],
				})
			},
			// 保存签证页到本地
			saveLocal() {
				let url = this.OrderDetails.visaPage
				uni.getSetting({
					success(res) {
						uni.downloadFile({
							url: url,
							success: function(res) {
								console.log(res);
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function(data) {
										uni.showToast({
											title: "保存成功",
											icon: "success",
											duration: 2000
										});
									},
									fail: function(err) {
										console.log(err);
									},
									complete(res) {
										console.log(res);
									}
								});
							}
						});
					}
				})
			},
			// 返回上一层
			toBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			clickEmail() {
				this.setData({
					emailShow: !this.emailShow
				})
			},
			onDownLoadZip() {
				let _self = this;
				ExportZip(_self.OrderDetails.Id).then(res => {
					let {
						data,
						status
					} = res
					if (status == 200) {
						// this.setData({

						// })
						this.setData({
							emailShow: !this.emailShow,
							wordUrl: data,
							wordType: 'zip',
							wordName: '团组入境包',
						})
					} else {
						uni.showToast({
							title: '发送异常，请稍后再试！',
							icon: 'error',
							duration: 2000
						})
					}
				})
			},
			sendEmail() {
				console.log("sdgds", this.email)
				if (!(/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$/.test(this
						.email))) {
					this.setData({
						emailMsg: "请输入正确的邮箱"
					})
					return false
				} else {
					this.setData({
						emailMsg: "",
						emailText: "发送中",
					})
					sendEmailByUrl({
							url: this.wordUrl,
							name: this.wordName,
							email: this.email
						})
						.then(res => {

							this.setData({
								emailShow: false,
								emailText: "发送"
							})
							if (res.status == 200) {
								uni.showToast({
									title: '发送成功',
									icon: 'success',
									duration: 2000
								})
							} else {
								uni.showToast({
									title: '发送异常，请稍后再试！',
									icon: 'error',
									duration: 2000
								})
							}
						})
				}


			},
			onInput(e) {
				this.setData({
					email: e.detail.value
				})
				if (this.email.length > 5 && !(
						/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$/.test(this
							.email)
					)) {
					this.setData({
						emailMsg: "请输入正确的邮箱"
					})
				} else {
					this.setData({
						emailMsg: ""
					})
				}
			},
			// 跳转产品
			tapCountryDetail() {
				// console.log(this)
				uni.navigateTo({
					url: '/pages/visa/detail?id=' + this.visa.VisaId,
				})
			},

			// 打开原因弹层
			_openRemark() {
				this.setData({
					isRemark: true
				})
			},
			// 关闭原因弹层
			_closeRemark() {
				this.setData({
					isRemark: false
				})
			},
			// 退款原因选择
			onChange(event) {
				this.setData({
					remark: event.detail
				});
			},
			// 退款原因选择
			onClick(event) {
				const {
					name
				} = event.currentTarget.dataset;
				this.setData({
					remark: name
				});
			},

			// 单个人的退款申请
			async refundPassenger() {
				if (!this.remark) return getApp().Tips({
					title: '请选择退款原因!'
				})
				uni.showLoading({
					title: '请稍后'
				})
				let res = await refundPassenger({
					id: this.OrderDetails.Id,
					remark: this.remark
				})
				console.log(res, '单个人的退款申请')
				if (res.status == 200) {
					uni.showToast({
						title: '退款申请成功',
						icon: 'success',
						duration: 2000
					})
					this.getPassenger();
				} else {
					uni.showToast({
						title: '退款申请失败',
						duration: 2000
					})
				}
				this._closeRemark();
			},
		}
	};
</script>

<style lang="scss" scoped>
	$imgUrl: "https://file.aavisa.com/001";

	.iconn image {
		width: 12rpx;
	}

	.look .icon image {

		width: 10rpx;
		margin-left: 13rpx;
	}

	uni-page-body {
		height: 100%;
		background: #f5f6f8;
	}

	.custum-head {
		height: 80rpx;
		background-color: #1c71f4;
	}

	.downloadVisa {
		width: 100%;
		height: 100%;
		background: #f5f6f8;
		font-family: PingFang SC;

		.headBac {
			background: url($imgUrl + "/images/entryOrder/downBac.png") no-repeat center;
			background-size: cover;
		}

		.head {
			display: flex;
			padding: 0 23rpx;
			height: 90rpx;
			align-items: center;
			font-weight: bold;
			font-size: 32rpx;
			color: #fff;
			background: #1c71f4;

			.title {
				font-weight: bold;
				font-size: 32rpx;
			}
		}

		.signOut {
			padding: 80rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.img {
				image {
					width: 280rpx;
					height: 164rpx;
				}
			}

			.success {
				margin-top: 12rpx;
				font-weight: 500;
				color: #222222;
				font-weight: bold;
				font-size: 38rpx;
				color: #00193c;
			}
		}

		.itemBodyTitle {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 46rpx;
			padding: 0 32rpx;

			image {
				width: 50rpx;
				height: 50rpx;
				margin-right: 12rpx;
				border-radius: 50%;
				background: #ffffff;
			}

			.txt {
				font-weight: bold;
				font-size: 32rpx;
				color: #101d34;
			}
		}

		.look {
			display: flex;
			font-weight: bold;
			font-size: 28rpx;
			color: #1c71f4;
			justify-content: center;
			margin-top: 10rpx;
		}

		.signOutPersonInfo {
			padding: 0rpx;

			// margin-top: 32rpx;
			.content {
				// height: 388rpx;
				// background: #ffffff;
				// box-shadow: 0rpx 1rpx 16rpx 0rpx rgba(143, 172, 162, 0.15);
				// border-radius: 30rpx;
				padding: 24rpx 32rpx 32rpx 32rpx;

				.signOutInfo {
					display: flex;
					justify-content: center;
					align-items: center;
					font-weight: 500;
					font-size: 46rpx;
					color: #222222;

					.icon_img {
						width: 64rpx;
						height: 64rpx;
						margin-right: 24rpx;
						position: relative;
						top: 7rpx;
					}
				}

				.itemPerson {
					border-radius: 20rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 0 50rpx 0 46rpx;
					margin-top: 20rpx;
					height: 103rpx;
					background: #ffffff;

					.leftInfo {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.name {
							font-size: 26rpx;
							color: #222222;
							margin-right: 21rpx;
							font-weight: 26rpx;
						}

						.allPerson {
							border-radius: 0 20rpx 0 20rpx;
							padding: 6rpx 14rpx;
							color: #fff;
							background: rgba(28, 113, 244, 0.1);
							border-radius: 5rpx;
							font-weight: 500;
							font-size: 24rpx;
							color: #1c71f4;
						}
					}

					.downLoad {
						font-weight: bold;
						font-size: 28rpx;
						color: #1c71f4;
					}
				}
			}
		}
	}

	.progress-container {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		background: rgba(0, 0, 0, .2);
		width: 750rpx;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;

		.progress-box {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 30rpx;

			.text {
				margin-bottom: 20rpx;
			}
		}
	}
</style>